package net.minhdiep.androiddialoglistener.util;
/*
 * User: Minh Diep
 * Date: 5/18/13
 * Time: 10:54 PM
 */

import android.app.Activity;
import android.os.AsyncTask;
import org.xmlpull.v1.XmlPullParserException;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URL;

public class DownloadXml extends AsyncTask<String, Integer, String> {

    private Activity activity;
    OnTaskListener onTaskListener;

    public DownloadXml(Activity activity){
        onTaskListener = (OnTaskListener) activity;
    }


    @Override
    protected String doInBackground(String... strings) {
        try {
            return downloadUrl(strings[0]);
        } catch (XmlPullParserException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
        onTaskListener.downloadFinish(s);
    }

    private String convertStreamToString(InputStream is) {
        java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
        return s.hasNext() ? s.next() : "";
    }

    private String downloadUrl(String string) throws IOException, XmlPullParserException {
        InputStream is = null;
        try {
            URL url = new URL(string);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(10000 /* milliseconds */);
            conn.setConnectTimeout(10000 /* milliseconds */);
            conn.setRequestMethod("GET");
            conn.connect();
            int response = conn.getResponseCode();
            if (response == 200) {
                is = conn.getInputStream();
                return convertStreamToString(is);
            } else
                return null;
        } catch (SocketTimeoutException e) {
            return null;
        } finally {
            if (is != null) {
                is.close();
            }
        }
    }

    public interface OnTaskListener{
        public void downloadFinish(String result);
    }
}
